package com.example.cloud.service.business.reservation.impl;

import com.example.cloud.dao.business.reservation.ScoreRecordRepository;
import com.example.cloud.model.statistics.ScoreRecord;
import com.example.cloud.model.system.User;
import com.example.cloud.service.business.reservation.ScoreRecordService;
import com.example.cloud.utils.BusinessUtil;
import com.example.cloud.utils.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * Created by wangtao on 2018/5/17.
 */
@Service
public class ScoreRecordServiceImpl implements ScoreRecordService {

    @PersistenceContext
    EntityManager em;

    @Autowired
    private ScoreRecordRepository scoreRecordRepository;

    @Override
    @Transactional
    public void doSave(ScoreRecord record) {
        StringBuilder sql = new StringBuilder("update basic_patient");
        int type = record.getType();
        // 1：加分 2：减分
        if (type == 1) {
            sql.append(" set score = score + :score");
        } else if (type == 2) {
            sql.append(" set score = score - :score");
        }
        sql.append(" where id = :id");
        Query q = em.createNativeQuery(sql.toString());
        q.setParameter("score", record.getScore());
        q.setParameter("id", record.getPatientId());
        q.executeUpdate();
        // 同步会员信息
        sql = new StringBuilder("update member set score  = (select score from basic_patient where id = :id) where patient_id = :id");
        q = em.createNativeQuery(sql.toString());
        q.setParameter("id", record.getPatientId());
        q.executeUpdate();
        // 保存操作记录
        User u = RequestUtil.getLoginUser();
        record.setAccountId(u.getAccountId());
        record.setOrganId(u.getOrganId());
        record.setOrganName(u.getOrganName());
        BusinessUtil.appendRecord(record);
        scoreRecordRepository.save(record);
    }

    @Override
    @Transactional
    public void doDelete(List<Long> ids) {
        scoreRecordRepository.deleteByIdIn(ids);
    }
}
